package taskmanage

import (
	//"fmt"
	"errors"
	"jiabo/appframework/libs/db"
	"labix.org/v2/mgo"
	"labix.org/v2/mgo/bson"
)

//人员部门关系表，用来记录每个用户加入了哪些部门
type UserOrg struct {
	Id       bson.ObjectId `bson:"_id,omitempty" json:"-"`
	UserName string        `bson:"userName" json:"userName"`
	OrgOid   string        `bson:"orgOid" json:"orgOid"`
}

func (userorg *UserOrg) CheckIfUserorgExist() (result bool, searchErr error) {
	searchErr = nil
	searchResults := UserOrg{}

	query := func(c *mgo.Collection) error {
		fn := c.Find(bson.M{"userName": userorg.UserName, "orgOid": userorg.OrgOid}).One(&searchResults)
		return fn
	}
	search := func() error {
		return db.WithCollection("userorg", query)
	}
	err := search()
	if err != nil {
		searchErr = err
	}

	if searchResults.Id != "" {
		result = true
	} else {
		result = false
	}
	return
}

func (userorg *UserOrg) Save() error {
	//判断如果部门已经存在，就更新，如果不存在就插入。
	ifUserOrgExist, err := userorg.CheckIfUserorgExist()
	if err != nil {
		//return err
	}
	if ifUserOrgExist {
		return errors.New("exist")
	} else {
		insert := func(c *mgo.Collection) error {

			fn := c.Insert(userorg)
			return fn
		}

		insertExec := func() error {
			return db.WithCollection("userorg", insert)
		}

		err := insertExec()
		return err
	}
	return nil
}

func (userorg *UserOrg) Delete() error {
	//判断如果部门已经存在，就更新，如果不存在就插入。
	ifUserOrgExist, err := userorg.CheckIfUserorgExist()
	if err != nil {
		//return err
	}
	if ifUserOrgExist {
		delet := func(c *mgo.Collection) error {
			fn := c.Remove(bson.M{"userName": userorg.UserName, "orgOid": userorg.OrgOid})
			return fn
		}

		deleteExec := func() error {
			return db.WithCollection("userorg", delet)
		}

		err := deleteExec()
		return err
	}
	return nil
}

func GetOrgnizationByUsername(userName string) (userorg []UserOrg, searchErr error) {
	searchErr = nil
	//department = nil
	searchResults := []UserOrg{}

	query := func(c *mgo.Collection) error {
		fn := c.Find(bson.M{"userName": userName}).All(&searchResults)
		return fn
	}
	search := func() error {
		return db.WithCollection("userorg", query)
	}
	err := search()
	if err != nil {
		searchErr = err
		return
	}

	userorg = searchResults
	return
}

func GetUsernameByOrgoid(orgoid string) (userorg []UserOrg, searchErr error) {
	searchErr = nil
	//department = nil
	searchResults := []UserOrg{}

	query := func(c *mgo.Collection) error {
		fn := c.Find(bson.M{"orgOid": orgoid}).All(&searchResults)
		return fn
	}
	search := func() error {
		return db.WithCollection("userorg", query)
	}
	err := search()
	if err != nil {
		searchErr = err
		return
	}

	userorg = searchResults
	return
}
